// Copyright 2012 Google Inc. All Rights Reserved.

package adwords.axis.v201109.misc;

import com.google.api.ads.adwords.axis.v201109.cm.Dimensions;
import com.google.api.ads.adwords.axis.v201109.cm.Image;
import com.google.api.ads.adwords.axis.v201109.cm.Media;
import com.google.api.ads.adwords.axis.v201109.cm.MediaMediaType;
import com.google.api.ads.adwords.axis.v201109.cm.MediaServiceInterface;
import com.google.api.ads.adwords.axis.v201109.cm.MediaSize;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServices;
import com.google.api.ads.common.lib.auth.ClientLoginTokens;
import com.google.api.ads.common.lib.utils.ImageUtils;
import com.google.api.ads.common.lib.utils.MapUtils;

import java.util.Map;

/**
 * This example uploads an image. To get images, run GetAllImagesAndVideos.java.
 *
 * Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 *
 * Tags: MediaService.upload
 *
 * @author Kevin Winter
 */
public class UploadImage {

  public static void main(String[] args) throws Exception {
    // Get a ClientLogin AuthToken.
    String clientLoginToken = new ClientLoginTokens(ClientLoginTokens.ADWORDS_SERVICE).fromFile();

    // Construct an AdWordsSession.
    AdWordsSession session =
        new AdWordsSession.Builder().fromFile().withClientLoginToken(clientLoginToken).build();

    runExample(session);
  }

  static void runExample(AdWordsSession session) throws Exception {
    // Get the MediaService.
    MediaServiceInterface mediaService =
        new AdWordsServices().get(session, MediaServiceInterface.class);

    // Create image.
    Image image = new Image();
    image.setData(new ImageUtils().getImageDataFromUrl("http://goo.gl/HJM3L"));
    image.setType(MediaMediaType.IMAGE);

    Media[] media = new Media[] {image};

    // Upload image.
    Media[] result = mediaService.upload(media);

    // Display images.
    image = (Image) result[0];
    Map<MediaSize, Dimensions> dimensions = new MapUtils().toMap(image.getDimensions());
    System.out.println("Image with id '" + image.getMediaId() + "', dimensions '"
        + dimensions.get(MediaSize.FULL).getWidth() + "x"
        + dimensions.get(MediaSize.FULL).getHeight() + "', and MIME type '" + image.getMediaType()
        + "' was uploaded.");
  }
}
